package netty.http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import java.net.URI;

/**
 * SimpleChannelInboundHandler 是ChannelInboundHandlerAdapter的子类
 * HttpObject 客服端和服务端相互通讯的数据被封装成HttpObject
 *
 * @Description http
 * @Author 李龙平
 * @Date 2020/10/12 14:43
 */
public class HttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {

    //读取客服端发送的消息

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, HttpObject msg) throws Exception {
        //判断msg是是不是httpRequest请求
        if (msg instanceof HttpRequest) {
            //不同浏览器的channelHandlerContext的hashCode不同
            //获取httpRequest
            HttpRequest request = (HttpRequest)msg;
            URI uri = new URI(request.uri());
            if ("/favicon.ico".equals(uri.getPath())) {
                System.out.println("不做处理");
                return;
            }

            //恢复信息给浏览器
            ByteBuf buf = Unpooled.copiedBuffer("hello,  我是服务器", CharsetUtil.UTF_8);
            //构造httpResponse
            FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_0, HttpResponseStatus.OK, buf);

            response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH, buf.readableBytes());

            channelHandlerContext.writeAndFlush(response);

        }
    }
}
